// script.js
// 全局变量 
let currentUser = JSON.parse(localStorage.getItem('currentUser')); 
let darkMode = localStorage.getItem('darkMode') === 'true';

// 页面加载初始化 
document.addEventListener('DOMContentLoaded', () => {
    initTheme();
    initUserState();
    initEventListeners();
    checkLoginStatus();
    loadUserList();
    searchFiles();
});

// 初始化主题 
function initTheme() {
    const themeToggle = document.getElementById('theme-toggle'); 
    if (themeToggle) {
        themeToggle.textContent = darkMode ? '☀️ 浅色模式' : '🌙 深色模式';
        if (darkMode) {
            document.body.classList.add('dark-mode'); 
        }
        themeToggle.addEventListener('click', toggleTheme);
    }
}

// 初始化用户状态 
function initUserState() {
    if (currentUser) {
                // 设置上传表单的用户名 
                const uploadUsername = document.getElementById('upload-username'); 
                if (uploadUsername) {
                    uploadUsername.value = currentUser.username; 
                }
    }


}
// 初始化个人资料表单
function initProfileForm() {
    const profileForm = document.getElementById('profile-form');
    if (profileForm) {
        const currentUser = JSON.parse(localStorage.getItem('currentUser'));
        if (currentUser) {
            document.getElementById('username').value = currentUser.username;
            document.getElementById('email').value = currentUser.email;
        }

        profileForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(profileForm);
            const username = formData.get('username');
            const email = formData.get('email');
            const password = formData.get('password');
            const avatarFile = formData.get('avatar');

            try {
                const response = await fetch('/update-profile', {
                    method: 'POST',
                    headers: {
                        'Authorization': JSON.stringify(currentUser)
                    },
                    body: formData
                });

                if (response.ok) {
                    const updatedUser = await response.json();
                    localStorage.setItem('currentUser', JSON.stringify(updatedUser));
                    alert('个人资料更新成功');
                    window.location.href = 'index.html';
                } else {
                    const error = await response.text();
                    alert(`更新失败: ${error}`);
                }
            } catch (error) {
                alert('网络错误，请稍后重试');
            }
        });
    }
}
// 初始化事件监听 
function initEventListeners() {
    // 登录表单提交 
    const loginForm = document.getElementById('login-form'); 
    if (loginForm) {
        loginForm.addEventListener('submit', async (e) => {
            e.preventDefault(); 
            const formData = new FormData(loginForm);
            try {
                const response = await fetch('/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(Object.fromEntries(formData)) 
                });
                
                if (response.ok)  {
                    const user = await response.json(); 
                    localStorage.setItem('currentUser', JSON.stringify(user)); 
                    window.location.href = 'index.html'; 
                } else {
                    const error = await response.text(); 
                    alert(`登录失败: ${error}`);
                }
            } catch (error) {
                alert('网络错误，请稍后重试');
            }
        });
    }

    // 注册表单提交 
    const registerForm = document.getElementById('register-form'); 
    if (registerForm) {
        registerForm.addEventListener('submit', async (e) => {
            e.preventDefault(); 
            const formData = new FormData(registerForm);
            try {
                const response = await fetch('/register', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(Object.fromEntries(formData)) 
                });
                
                const result = await response.text(); 
                if (response.ok)  {
                    alert('注册成功，请登录');
                    window.location.href = 'login.html'; 
                } else {
                    alert(`注册失败: ${result}`);
                }
            } catch (error) {
                alert('网络错误，请稍后重试');
            }
        });
    }

    // 文件上传表单 
    const uploadForm = document.getElementById('upload-form'); 
    if (uploadForm) {
        uploadForm.addEventListener('submit', async (e) => {
            e.preventDefault(); 
            
            if (!currentUser) {
                alert('请先登录后再上传文件');
                window.location.href = 'login.html'; 
                return;
            }
            
            const formData = new FormData(uploadForm);
            try {
                const response = await fetch('/upload', {
                    method: 'POST',
                    body: formData 
                });
                
                const result = await response.text(); 
                if (response.ok)  {
                    alert('文件上传成功');
                    uploadForm.reset(); 
                } else {
                    alert(`上传失败: ${result}`);
                }
            } catch (error) {
                alert('上传过程中发生错误');
            }
        });
    }

    // 文件搜索功能 
    const searchButton = document.getElementById('search-button'); 
    if (searchButton) {
        searchButton.addEventListener('click', searchFiles);
    }

    // 退出登录 
    const logoutLink = document.getElementById('logout-link'); 
    if (logoutLink) {
        logoutLink.addEventListener('click', (e) => {
            e.preventDefault(); 
            localStorage.removeItem('currentUser'); 
            window.location.href = 'index.html'; 
        });
    }

    // 发送验证码
    const sendVerificationCodeButton = document.getElementById('send-verification-code');
    if (sendVerificationCodeButton) {
        sendVerificationCodeButton.addEventListener('click', async () => {
            const emailInput = document.getElementById('email');
            const email = emailInput.value;
            if (!email) {
                alert('请输入邮箱');
                return;
            }
            try {
                const response = await fetch('/send-verification-code', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ email })
                });
                if (response.ok) {
                    const data = await response.json();
                    verificationCode = data.verificationCode;
                    alert('验证码已发送，请查收邮箱');
                } else {
                    const error = await response.text();
                    alert(`发送验证码失败: ${error}`);
                }
            } catch (error) {
                alert('网络错误，请稍后重试');
            }
        });
    }

    // 忘记密码表单提交
    const forgetPasswordForm = document.getElementById('forget-password-form');
    if (forgetPasswordForm) {
        forgetPasswordForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(forgetPasswordForm);
            const email = formData.get('email');
            const verificationCode = formData.get('verificationCode');
            const newPassword = formData.get('newPassword');

            try {
                const response = await fetch('/reset-password', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ email, verificationCode, newPassword })
                });

                const result = await response.text();
                if (response.ok) {
                    alert('密码重置成功，请登录');
                    window.location.href = 'login.html';
                } else {
                    alert(`重置密码失败: ${result}`);
                }
            } catch (error) {
                alert('网络错误，请稍后重试');
            }
        });
    }

    // 切换用户
    const userList = document.getElementById('user-list');
    if (userList) {
        userList.addEventListener('click', async (e) => {
            const target = e.target;
            if (target.tagName === 'LI') {
                const username = target.getAttribute('data-username');
                if (confirm(`是否登录用户 ${username}?`)) {
                    try {
                        const response = await fetch('/switch-user', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ username })
                        });
                        if (response.ok) {
                            const user = await response.json();
                            localStorage.setItem('currentUser', JSON.stringify(user));
                            window.location.href = 'index.html';
                        } else {
                            const error = await response.text();
                            alert(`切换用户失败: ${error}`);
                        }
                    } catch (error) {
                        alert('网络错误，请稍后重试');
                    }
                }
            }
        });
    }
    initProfileForm();
}

// 切换主题 
function toggleTheme() {
    darkMode = !darkMode;
    localStorage.setItem('darkMode', darkMode);
    document.body.classList.toggle('dark-mode'); 
    document.getElementById('theme-toggle').textContent = 
        darkMode ? '☀️ 浅色模式' : '🌙 深色模式';
}

// 搜索文件 
// 搜索文件 
// 搜索文件 
async function searchFiles() {
    const username = document.getElementById('search-username').value; 
    const repository = document.getElementById('search-repository').value; 
    const resultsContainer = document.getElementById('download-results'); 
    const outputLog =`存储库搜索操作:
        执行操作的用户:${currentUser.username}
        搜索用户名:${username}
        搜索存储库:${repository}`;
    fetch(`/output/message/${outputLog}`);

    if (!username && !repository) {
        // 如果没有搜索条件，加载所有存储库
        try {
            const allUsers = await readAllUsers();
            let allRepositories = [];
            allUsers.forEach(user => {
                allRepositories = allRepositories.concat(user.repositories.map(repo => ({ ...repo, username: user.username })));
            });
            displayResults(allRepositories, null);
        } catch (error) {
            resultsContainer.innerHTML = '<p>加载存储库过程中发生错误</p>';
        }
        return;
    }
    
    try {
        const response = await fetch(`/repositories/${username}`);
        if (response.ok)  {
            const repositories = await response.json(); 
            const filtered = repositories.filter(repo => 
                repository ? repo.name.includes(repository)  : true 
            );
            
            displayResults(filtered, username);
        } else {
            resultsContainer.innerHTML = '<p>未找到匹配的存储库</p>';
        }
    } catch (error) {
        resultsContainer.innerHTML = '<p>搜索过程中发生错误</p>';
    }
}

// 读取所有用户数据
async function readAllUsers() {
    try {
        const data = await fs.readFile(usersFilePath, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        return [];
    }
}
// 显示搜索结果 
function displayResults(repositories, username, page = 1, pageSize = 10) {
    const resultsContainer = document.getElementById('download-results'); 
    const isCurrentUser = currentUser && currentUser.username === username;
    
    if (repositories.length === 0) {
        resultsContainer.innerHTML = '<p>未找到匹配的存储库</p>';
        return;
    }
    
    // 分页逻辑
    const totalPages = Math.ceil(repositories.length / pageSize);
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedRepos = repositories.slice(startIndex, endIndex);

    let html = '';
    paginatedRepos.forEach(repo => {
        html += `
            <div class="repository">
                <h3>${repo.name}  <small>上传者: ${username}</small></h3>
                <p>上传时间: ${new Date(repo.uploadDate).toLocaleString()}</p> 
                <ul class="file-list">
                    ${repo.files.map(file => `
                        <li>
                            <a href="/download/${repo.username}/${repo.name}/${file}" download>${file}</a>
                            ${isCurrentUser || currentUser.role === 'root' ? 
                                `<button class="delete-file" data-file="${file}" 
                                data-repo="${repo.name}"> 删除</button>` : ''}
                        </li>
                    `).join('')}
                </ul>
                ${isCurrentUser || currentUser.role === 'root' ? `
                    <div class="repo-actions">
                        <button class="delete-repo" data-repo="${repo.name}"> 删除整个存储库</button>
                        <button class="add-files" data-repo="${repo.name}"> 添加更多文件</button>
                    </div>
                ` : ''}
            </div>
        `;
    });

    // 添加分页按钮
    let paginationHtml = '<div class="pagination">';
    if (page > 1) {
        paginationHtml += `<button class="pagination-button" data-page="${page - 1}">上一页</button>`;
    }
    for (let i = 1; i <= totalPages; i++) {
        paginationHtml += `<button class="pagination-button ${i === page ? 'active' : ''}" data-page="${i}">${i}</button>`;
    }
    if (page < totalPages) {
        paginationHtml += `<button class="pagination-button" data-page="${page + 1}">下一页</button>`;
    }
    paginationHtml += '</div>';

    resultsContainer.innerHTML = html + paginationHtml;

    // 添加删除文件事件 
    document.querySelectorAll('.delete-file').forEach(button => {
        button.addEventListener('click', deleteFile);
    });

    // 添加删除存储库事件 
    document.querySelectorAll('.delete-repo').forEach(button => {
        button.addEventListener('click', deleteRepository);
    });

    // 添加分页按钮事件
    document.querySelectorAll('.pagination-button').forEach(button => {
        button.addEventListener('click', (e) => {
            const newPage = parseInt(e.target.getAttribute('data-page'));
            displayResults(repositories, username, newPage, pageSize);
        });
    });
}

// 删除文件 
async function deleteFile(e) {
    if (!confirm('确定要删除这个文件吗？')) return;
    
    const file = e.target.dataset.file; 
    const repo = e.target.dataset.repo; 
    
    try {
        const response = await fetch(`/repositories/${currentUser.username}/${repo}/${file}`, {
            method: 'DELETE'
        });
        
        if (response.ok)  {
            alert('文件删除成功');
            searchFiles(); // 刷新列表 
        } else {
            alert('删除文件失败');
        }
    } catch (error) {
        alert('删除过程中发生错误');
    }
}

// 删除存储库 
async function deleteRepository(e) {
    if (!confirm('确定要删除整个存储库吗？这将删除所有文件！')) return;
    
    const repo = e.target.dataset.repo; 
    
    try {
        const response = await fetch(`/repositories/${currentUser.username}/${repo}`, {
            method: 'DELETE'
        });
        
        if (response.ok)  {
            alert('存储库删除成功');
            searchFiles(); // 刷新列表 
        } else {
            alert('删除存储库失败');
        }
    } catch (error) {
        alert('删除过程中发生错误');
    }
}

// 检查登录状态
function checkLoginStatus() {
    if (window.location.pathname === '/upload.html' && !currentUser) {
        alert('请先登录后再上传文件');
        window.location.href = 'login.html';
    }
}

// 加载用户列表
// 加载用户列表
// 加载用户列表
async function loadUserList() {
    if (window.location.pathname === '/user-list.html') {
        if (currentUser.role !== 'root') {
            document.getElementById('user-list-container').innerHTML = `
                <h1 style="text-align: center;">404</h1>
                <q style="text-align: center;">您没有权限</q>
                <button style="display: block; margin: 20px auto;" onclick="window.location.href='index.html'">返回首页</button>
            `;
            return;
        }

        try {
            const response = await fetch('/users', {
                headers: {
                    'Authorization': JSON.stringify(currentUser)
                }
            });
            if (response.ok) {
                const users = await response.json();
                displayUsers(users, 1, 25);
            } else {
                alert('加载用户列表失败');
            }
        } catch (error) {
            alert('网络错误，请稍后重试');
        }
    }
}

// 显示用户列表
function displayUsers(users, page = 1, pageSize = 25) {
    const userListContainer = document.getElementById('user-list-container');
    const userList = document.getElementById('user-list');
    const paginationContainer = document.getElementById('pagination');
    
    if (users.length === 0) {
        userList.innerHTML = '<tr><td colspan="6">未找到用户</td></tr>';
        paginationContainer.innerHTML = '';
        return;
    }
    
    // 分页逻辑
    const totalPages = Math.ceil(users.length / pageSize);
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedUsers = users.slice(startIndex, endIndex);

    let html = '';
    paginatedUsers.forEach(user => {
        html += `
            <tr>
                <td><input type="text" value="${user.username}" data-username="${user.username}" data-field="username"></td>
                <td><input type="email" value="${user.email}" data-username="${user.username}" data-field="email"></td>
                <td>
                    <select data-username="${user.username}" data-field="role">
                        <option value="default" ${user.role === 'default' ? 'selected' : ''}>普通用户</option>
                        <option value="root" ${user.role === 'root' ? 'selected' : ''}>管理员</option>
                    </select>
                </td>
                <td><button class="reset-password" data-username="${user.username}">重置密码</button></td>
                <td><button class="delete-user" data-username="${user.username}">删除用户</button></td>
                <td><button class="save-user" data-username="${user.username}">确认修改</button></td>
                <td><button class="login-as-user" data-username="${user.username}">登录此用户</button></td>
            </tr>
        `;
    });

    userList.innerHTML = html;

    // 添加重置密码事件
    document.querySelectorAll('.reset-password').forEach(button => {
        button.addEventListener('click', resetUserPassword);
    });

    // 添加删除用户事件
    document.querySelectorAll('.delete-user').forEach(button => {
        button.addEventListener('click', deleteUser);
    });

    // 添加保存用户信息事件
    document.querySelectorAll('input[data-username], select[data-username]').forEach(input => {
        input.addEventListener('change', saveUserInfo);
    });

    // 添加确认修改按钮事件
    document.querySelectorAll('.save-user').forEach(button => {
        button.addEventListener('click', saveUserInfo);
    });

    // 添加登录此用户按钮事件
    document.querySelectorAll('.login-as-user').forEach(button => {
        button.addEventListener('click', loginAsUser);
    });

    // 添加分页按钮
    let paginationHtml = '<div class="pagination">';
    if (page > 1) {
        paginationHtml += `<button class="pagination-button" data-page="${page - 1}">上一页</button>`;
    }
    for (let i = 1; i <= totalPages; i++) {
        paginationHtml += `<button class="pagination-button ${i === page ? 'active' : ''}" data-page="${i}">${i}</button>`;
    }
    if (page < totalPages) {
        paginationHtml += `<button class="pagination-button" data-page="${page + 1}">下一页</button>`;
    }
    paginationHtml += '</div>';

    paginationContainer.innerHTML = paginationHtml;

    // 添加分页按钮事件
    document.querySelectorAll('.pagination-button').forEach(button => {
        button.addEventListener('click', (e) => {
            const newPage = parseInt(e.target.getAttribute('data-page'));
            displayUsers(users, newPage, pageSize);
        });
    });
}

// 登录此用户
async function loginAsUser(e) {
    const username = e.target.getAttribute('data-username');
    if (!confirm(`是否登录用户 ${username}?`)) return;

    try {
        const response = await fetch('/switch-user', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username })
        });

        if (response.ok) {
            const user = await response.json();
            localStorage.setItem('currentUser', JSON.stringify(user));
            window.location.href = 'index.html';
        } else {
            const error = await response.text();
            alert(`切换用户失败: ${error}`);
        }
    } catch (error) {
        alert('网络错误，请稍后重试');
    }
}

// 保存用户信息
async function saveUserInfo(e) {
    const username = e.target.getAttribute('data-username');
    const field = e.target.getAttribute('data-field');
    const value = e.target.value;

    try {
        const response = await fetch('/update-user', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': JSON.stringify(currentUser)
            },
            body: JSON.stringify({ username, [field]: value })
        });

        if (response.ok) {
            alert('用户信息更新成功');
            loadUserList();
        } else {
            const error = await response.text();
            alert(`更新用户信息失败: ${error}`);
        }
    } catch (error) {
        alert('网络错误，请稍后重试');
    }
}

// 重置用户密码
async function resetUserPassword(e) {
    const username = e.target.getAttribute('data-username');
    const newPassword = prompt('请输入新密码:');
    if (!newPassword) return;

    try {
        const response = await fetch('/reset-password', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ email: username, verificationCode: 'dummy', newPassword })
        });

        if (response.ok) {
            alert('密码重置成功');
            loadUserList();
        } else {
            const error = await response.text();
            alert(`重置密码失败: ${error}`);
        }
    } catch (error) {
        alert('网络错误，请稍后重试');
    }
}

// 删除用户
async function deleteUser(e) {
    const username = e.target.getAttribute('data-username');
    if (!confirm(`是否删除用户 ${username}?`)) return;

    try {
        const response = await fetch('/delete-user', {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username })
        });

        if (response.ok) {
            alert('用户删除成功');
            loadUserList();
        } else {
            const error = await response.text();
            alert(`删除用户失败: ${error}`);
        }
    } catch (error) {
        alert('网络错误，请稍后重试');
    }
}

// 保存用户信息
async function saveUserInfo(e) {
    const username = e.target.getAttribute('data-username');
    const field = e.target.getAttribute('data-field');
    const value = e.target.value;

    try {
        const response = await fetch('/update-user', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': JSON.stringify(currentUser)
            },
            body: JSON.stringify({ username, [field]: value })
        });

        if (response.ok) {
            alert('用户信息更新成功');
            loadUserList();
        } else {
            const error = await response.text();
            alert(`更新用户信息失败: ${error}`);
        }
    } catch (error) {
        alert('网络错误，请稍后重试');
    }
}

// 添加用户
async function addUser(e) {
    e.preventDefault();
    const form = document.getElementById('add-user-form');
    const formData = new FormData(form);
    const username = formData.get('new-username');
    const password = formData.get('new-password');
    const email = formData.get('new-email');
    const role = formData.get('new-role');

    try {
        const response = await fetch('/add-user', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': JSON.stringify(currentUser)
            },
            body: JSON.stringify({ username, password, email, role })
        });

        if (response.ok) {
            alert('用户添加成功');
            form.reset();
            loadUserList();
        } else {
            const error = await response.text();
            alert(`添加用户失败: ${error}`);
        }
    } catch (error) {
        alert('网络错误，请稍后重试');
    }
}

// 初始化事件监听 
function initEventListeners() {
    // 登录表单提交 
    const loginForm = document.getElementById('login-form'); 
    if (loginForm) {
        loginForm.addEventListener('submit', async (e) => {
            e.preventDefault(); 
            const formData = new FormData(loginForm);
            try {
                const response = await fetch('/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(Object.fromEntries(formData)) 
                });
                
                if (response.ok)  {
                    const user = await response.json(); 
                    localStorage.setItem('currentUser', JSON.stringify(user)); 
                    window.location.href = 'index.html'; 
                } else {
                    const error = await response.text(); 
                    alert(`登录失败: ${error}`);
                }
            } catch (error) {
                alert('网络错误，请稍后重试');
            }
        });
    }

    // 注册表单提交 
    const registerForm = document.getElementById('register-form'); 
    if (registerForm) {
        registerForm.addEventListener('submit', async (e) => {
            e.preventDefault(); 
            const formData = new FormData(registerForm);
            try {
                const response = await fetch('/register', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(Object.fromEntries(formData)) 
                });
                
                const result = await response.text(); 
                if (response.ok)  {
                    alert('注册成功，请登录');
                    window.location.href = 'login.html'; 
                } else {
                    alert(`注册失败: ${result}`);
                }
            } catch (error) {
                alert('网络错误，请稍后重试');
            }
        });
    }

    // 文件上传表单 
    const uploadForm = document.getElementById('upload-form'); 
    if (uploadForm) {
        uploadForm.addEventListener('submit', async (e) => {
            e.preventDefault(); 
            
            if (!currentUser) {
                alert('请先登录后再上传文件');
                window.location.href = 'login.html'; 
                return;
            }
            
            const formData = new FormData(uploadForm);
            try {
                const response = await fetch('/upload', {
                    method: 'POST',
                    body: formData 
                });
                
                const result = await response.text(); 
                if (response.ok)  {
                    alert('文件上传成功');
                    uploadForm.reset(); 
                } else {
                    alert(`上传失败: ${result}`);
                }
            } catch (error) {
                alert('上传过程中发生错误');
            }
        });
    }

    // 文件搜索功能 
    const searchButton = document.getElementById('search-button'); 
    if (searchButton) {
        searchButton.addEventListener('click', searchFiles);
    }

    // 退出登录 
    const logoutLink = document.getElementById('logout-link'); 
    if (logoutLink) {
        logoutLink.addEventListener('click', (e) => {
            e.preventDefault(); 
            localStorage.removeItem('currentUser'); 
            window.location.href = 'index.html'; 
        });
    }

    // 发送验证码
    const sendVerificationCodeButton = document.getElementById('send-verification-code');
    if (sendVerificationCodeButton) {
        sendVerificationCodeButton.addEventListener('click', async () => {
            const emailInput = document.getElementById('email');
            const email = emailInput.value;
            if (!email) {
                alert('请输入邮箱');
                return;
            }
            try {
                const response = await fetch('/send-verification-code', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ email })
                });
                if (response.ok) {
                    const data = await response.json();
                    verificationCode = data.verificationCode;
                    alert('验证码已发送，请查收邮箱');
                } else {
                    const error = await response.text();
                    alert(`发送验证码失败: ${error}`);
                }
            } catch (error) {
                alert('网络错误，请稍后重试');
            }
        });
    }

    // 忘记密码表单提交
    const forgetPasswordForm = document.getElementById('forget-password-form');
    if (forgetPasswordForm) {
        forgetPasswordForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(forgetPasswordForm);
            const email = formData.get('email');
            const verificationCode = formData.get('verificationCode');
            const newPassword = formData.get('newPassword');

            try {
                const response = await fetch('/reset-password', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ email, verificationCode, newPassword })
                });

                const result = await response.text();
                if (response.ok) {
                    alert('密码重置成功，请登录');
                    window.location.href = 'login.html';
                } else {
                    alert(`重置密码失败: ${result}`);
                }
            } catch (error) {
                alert('网络错误，请稍后重试');
            }
        });
    }

    // 切换用户
    const userList = document.getElementById('user-list');
    if (userList) {
        userList.addEventListener('click', async (e) => {
            const target = e.target;
            if (target.tagName === 'LI') {
                const username = target.getAttribute('data-username');
                if (confirm(`是否登录用户 ${username}?`)) {
                    try {
                        const response = await fetch('/switch-user', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ username })
                        });
                        if (response.ok) {
                            const user = await response.json();
                            localStorage.setItem('currentUser', JSON.stringify(user));
                            window.location.href = 'index.html';
                        } else {
                            const error = await response.text();
                            alert(`切换用户失败: ${error}`);
                        }
                    } catch (error) {
                        alert('网络错误，请稍后重试');
                    }
                }
            }
        });
    }

    // 添加用户表单提交
    const addUserForm = document.getElementById('add-user-form');
    if (addUserForm) {
        addUserForm.addEventListener('submit', addUser);
    }

    initProfileForm();
}